﻿using System;
using System.IO.Packaging;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;

namespace FxFlowWindowBase.Win.Extension
{
	public static class ViewExtension
	{
		public static void LoadViewFromUri(this FrameworkElement userControl, string baseUri)
		{
			try
			{
				var resourceLocater = new Uri(baseUri, UriKind.Relative);
				var exprCa = (PackagePart)typeof(Application).GetMethod("GetResourceOrContentPart", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { resourceLocater });
				var stream = exprCa.GetStream();
				var uri = new Uri((Uri)typeof(BaseUriHelper).GetProperty("PackAppBaseUri", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null, null), resourceLocater);
				var parserContext = new ParserContext
				{
					BaseUri = uri
				};
				typeof(XamlReader).GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { stream, parserContext, userControl, true });
			}
			catch (Exception e)
			{
				throw new Exception($"加载Xaml错误: {e.Message}");
			}
		}
	}
}
